#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from string import Template

from tack.lib import json_app, content_headers, status_codes
from tack.lib.smtptools import message, send_message
from tack_ocie.api.util import state_def, build_empty_row_dict, fill_dict_from_form, build_columns_values_sql


get_schedule_columns = "SELECT * FROM ocie_schedule WHERE 1 = 0"
get_attendee_columns = "SELECT * FROM ocie_schedule_attendee WHERE 1 = 0"
get_notify_message = """
SELECT subject, markup
FROM message_template
WHERE keyword = 'ocie_appt_conf'
"""
insert = "INSERT INTO ocie_schedule"
insert_attendee = "INSERT INTO ocie_schedule_attendee"


def add(environ, start_response, state):
    form = environ['form']
    try:
        start = form['parsed_start'] = datetime.strptime(form['start'], '%Y-%m-%d %H:%M')
        finish = form['parsed_finish'] = datetime.strptime(form['finish'], '%Y-%m-%d %H:%M')
        if(start >= finish):
            raise ValueError
    except:
        start_response(status_codes.error, content_headers.default_plain())
        form['errored'] = True
        return ['Error']
    time_stamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    cursor = environ['connection'].cursor()
    cursor.execute(get_schedule_columns)
    rows = cursor.fetchall()
    cd = cursor.description
    state_dict = build_empty_row_dict(cd)
    state_dict = fill_dict_from_form(state_dict, cd, form)
    state_dict['state_key'] = state
    state_dict['state_start'] = "'" + time_stamp + "'"
    state_dict['creator'] = "'%s'" % environ.get('authrec', {}).get("login", "anonymous")
    del state_dict['state_finish']
    del state_dict['schedule_id']
    del state_dict['parent_id']
    sql = insert + build_columns_values_sql(state_dict)
    cursor.execute(sql)
    environ['connection'].commit()
    sql = 'SELECT CAST(@@IDENTITY AS INT)'
    cursor.execute(sql)
    form['schedule_id'] = schedule_id = cursor.fetchall()[0][0]
    form['attendee_ranks'] = form['attendee_ranks'] if isinstance(form['attendee_ranks'], list) else [form['attendee_ranks']]
    form['attendee_first_names'] = form['attendee_first_names'] if isinstance(form['attendee_first_names'], list) else [form['attendee_first_names']]
    form['attendee_last_names'] = form['attendee_last_names'] if isinstance(form['attendee_last_names'], list) else [form['attendee_last_names']]
    form['attendee_ssn'] = form['attendee_ssn'] if isinstance(form['attendee_ssn'], list) else [form['attendee_ssn']]
    attendees = zip(form['attendee_ranks'],form['attendee_first_names'],form['attendee_last_names'],form['attendee_ssn'])
    cursor.execute(get_attendee_columns)
    rows = cursor.fetchall()
    cd = cursor.description
    attendee_dict = build_empty_row_dict(cd)
    del attendee_dict['schedule_attendee_id']
    for attendee in attendees:
        form['rank'] = attendee[0]
        form['first_name'] = attendee[1]
        form['last_name'] = attendee[2]
        form['ssn'] = attendee[3]
        attendee_dict = fill_dict_from_form(attendee_dict, cd, form)
        sql = insert_attendee + build_columns_values_sql(attendee_dict)
        cursor.execute(sql)
        environ['connection'].commit()
    output = schedule_id
    return json_app(output)(environ, start_response)


def add_notify(environ):
    form = environ['form']
    conf = environ['tack.siteconfig']
    sndr = conf['ocie_pr_email']
    poc_email = form.get('poc_email')
    errored = form.get('errored')
    if not poc_email or errored:
        return
    cursor = environ['connection'].cursor()
    cursor.execute(get_notify_message)
    subject, markup = cursor.fetchone()
    subs = dict(day=form['parsed_start'].date().strftime("%d %b %Y").upper(),
                start=form['parsed_start'].time().strftime("%H:%M"),
                finish=form['parsed_finish'].time().strftime("%H:%M"),
                schedule_id=form['schedule_id'])
    msg = message(sndr, poc_email, subject, Template(markup).safe_substitute(subs))
    send_message(sndr,
                 [(poc_email, msg)],
                 conf['ocie_mail_host'],
                 username=conf['ocie_mail_user'],
                 password=conf['ocie_mail_pass'])


def add_resourced(environ, start_response):
    r = add(environ, start_response, state_def.RESOURCED)
    try:
        add_notify(environ)
    except:
        raise
    return r


def add_drafted(environ, start_response):
    form = environ['form']
    try:
        start = datetime.strptime(form['start'],'%Y-%m-%d %H:%M')
        finish = datetime.strptime(form['finish'],'%Y-%m-%d %H:%M')
        if(start >= finish):
            raise ValueError
    except:        
        form['start'] = datetime.now().strftime('%Y-%m-%d %H:%M')
        form['finish'] = ( datetime.now() + timedelta(minutes=1) ).strftime('%Y-%m-%d %H:%M')
    return add(environ, start_response, state_def.DRAFTED)
